package com.wr.spinkLock14;

import java.util.concurrent.atomic.AtomicInteger;
// 自旋锁第二种,有顺序的自旋锁。谁先调用lock就能先执行

/**
 * 每次都要查询一个serviceNum 服务号，影响性能（必须要到主内存读取，并阻止其他cpu修改）。
 */
public class TicketLock02 {
    private AtomicInteger                     serviceNum = new AtomicInteger();
    private AtomicInteger                     ticketNum  = new AtomicInteger();
    private static final ThreadLocal<Integer> LOCAL      = new ThreadLocal<Integer>();


    public void lock(){
        int myTicketNum = ticketNum.getAndIncrement(); // 原子加1并返回之前的数
        LOCAL.set(myTicketNum);
        while (myTicketNum != serviceNum.get()){};
    }

    public void unlock(){
        int myTicketNum = LOCAL.get();
        serviceNum.compareAndSet(myTicketNum,myTicketNum+1);
    }
}
